package com.itaming.lycheeframework.support.utils;

import lombok.experimental.UtilityClass;

import java.io.File;
import java.net.URL;

/**
 * Path工具类
 *
 * @author A.Ming
 */
@UtilityClass
public class PathUtil {

    public static final String FILE_PROTOCOL = "file";
    public static final String JAR_PROTOCOL = "jar";
    public static final String ZIP_PROTOCOL = "zip";
    public static final String FILE_PROTOCOL_PREFIX = "file:";
    public static final String JAR_FILE_SEPARATOR = "!/";

    /**
     * 获取jar包运行时的所在目录绝对路径
     *
     * @return 绝对路径
     */
    public static String getJarPath() {
        URL url = PathUtil.class.getResource(StringPool.SLASH);
        return toFilePath(url);
    }

    /**
     * URL转换为文件路径
     *
     * @param url URL
     * @return 文件路径
     */
    private static String toFilePath(URL url) {
        if (url == null) {
            return StringPool.EMPTY;
        }

        String protocol = url.getProtocol();
        String filePath = URLUtil.decode(url.getPath());
        assert filePath != null;

        if (FILE_PROTOCOL.equals(protocol)) {
            return new File(filePath).getParentFile().getParentFile().getAbsolutePath();
        }

        if (JAR_PROTOCOL.equals(protocol) || ZIP_PROTOCOL.equals(protocol)) {
            int pos = filePath.indexOf(JAR_FILE_SEPARATOR);
            if (pos > 0) {
                filePath = filePath.substring(0, pos);
            }
            if (filePath.startsWith(FILE_PROTOCOL_PREFIX)) {
                filePath = filePath.substring(FILE_PROTOCOL_PREFIX.length());
            }

            File file = new File(filePath);

            return file.isDirectory() ? file.getAbsolutePath() : file.getParentFile().getAbsolutePath();
        }

        return filePath;
    }

}
